#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>

#define SLOG(level,format,args...) \
     do{printf("[%s][%s:%d]",#level,__func__,__LINE__);\
     printf(format,##args);}while(0)

int check_path_integrity(const char *path)
{
	if(path == NULL)
	{
		SLOG(ERR,"device is null!\n");
		return -1;
	}
#if 1 
	struct dirent **namelist;
	char fname[128]={0};
	int n, ret = 0;
	struct stat st;

	n = scandir(path, &namelist, NULL, alphasort);
	if (n < 0)
	{
		SLOG(ERR,"scandir error:errno = %d,%s\n",errno,strerror(errno));
		return -1;
	}
	else 
	{
		while (n--) 
		{
			printf("%s\n", namelist[n]->d_name);
			if(!ret && strcmp(namelist[n]->d_name,".") && strcmp(namelist[n]->d_name,".."))
			{
				snprintf(fname,sizeof(fname),"%s/%s",path,namelist[n]->d_name);
				memset(&st,0,sizeof(st));
				if(!stat(fname,&st) && S_ISDIR(st.st_mode))
					ret = check_path_integrity(fname);
			}
			free(namelist[n]);
		}
		free(namelist);
	}
#else
	char cmd[64]={0};
	int ret = 0;
	snprintf(cmd,sizeof(cmd),"ls %s",path);
	ret = system(cmd);
	if(ret != 0)
	{
		SLOG(ERR,"ls %s has error,ret = %d\n",path,ret);
		if(WIFEXITED(ret))
			SLOG(ERR,"ls return value = %d\n",WEXITSTATUS(ret));
		return -1;
	}
#endif
	if(ret < 0)
		return -1;

	/** check writable */
    char testfile[64]={0};
    int tfd = -1;
    snprintf(testfile,sizeof(testfile),"%s/.testw",path);
    remove(testfile);
    if((tfd=open(testfile,O_CREAT|O_WRONLY,0777))<0)
    {
        SLOG(ERR,"test path %s write fail!\n",path);
        return -1;
    }
    close(tfd);

	return 0;
}

int main(int argc,char *argv[])
{
	int ret = 0;

	if(argc != 2)
	{
		fprintf(stderr,"Usage: %s <path>\n",strrchr(argv[0],'/')+1);
		exit(1);
	}
	ret = check_path_integrity(argv[1]);
	if(ret < 0)
	{
		printf("check_path_integrity fail:ret = %d\n",ret);
		exit(2);
	}
	return ret;
}

